package com.zzyl.nursing.service.impl;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 入住Service业务层处理
 *
 * @author xyc
 * @date 2025-07-23
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService {
    @Autowired
    private CheckInMapper checkInMapper;

    @Autowired
    private ElderMapper elderMapper;

    @Autowired
    private BedMapper bedMapper;

    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    @Autowired
    private ContractMapper contractMapper;

    /**
     * 查询入住
     *
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id) {
        return getById(id);
    }

    /**
     * 查询入住列表
     *
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn) {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn) {
        return save(checkIn) ? 1 : 0;
    }

    /**
     * 修改入住
     *
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn) {
        return updateById(checkIn) ? 1 : 0;
    }

    /**
     * 批量删除入住
     *
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除入住信息
     *
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Transactional
    @Override
    public void apply(CheckInApplyDto dto) {
        //1.检验老人是否入住
        Elder elder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery().eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo()));
        if (elder != null) {
            return;
        }
        //2.更新床位状态为已入住
        Bed bed = bedMapper.selectById(dto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateById(bed);
        //3.新增或更新老人
        elder = saveElder(dto, bed);
        //4.新增签约办理
        saveContract(dto, elder);
        //5.新增入住
        CheckIn checkIn = saveCheckIn(dto, elder);
        //6.新增入住配置
        saveCheckInConfig(dto, checkIn);
    }

    /**
     * 查询入住详情
     *
     * @param id
     * @return
     */
    @Override
    public CheckInDetailVo detail(Long id) {
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        //查询入住信息
        CheckIn checkIn = checkInMapper.selectCheckInById(id);
        //查询老人信息
        Long elderId = checkIn.getElderId();
        Elder elder = elderMapper.selectElderById(elderId);
        CheckInElderVo checkInElderVo = selectCheckInElderVo(elder);
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        //查询合同
        Contract contract = contractMapper.selectOne(Wrappers.<Contract>lambdaQuery().eq(Contract::getElderId, elderId));
        checkInDetailVo.setContract(contract);
        //查询入住配置信息
        Long checkInId = checkIn.getId();
        CheckInConfigVo checkInConfigVo = selectCheckInConfigVo(elder, contract, checkInId);
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        // 查询老人家属信息
        List<ElderFamilyVo> elderFamilyVos = selectElderFamilyVoList(checkIn);
        checkInDetailVo.setElderFamilyVoList(elderFamilyVos);
        return checkInDetailVo;
    }
    /**
     * 查询老人家属信息
     * @param checkIn
     * @return
     */
    public List<ElderFamilyVo> selectElderFamilyVoList(CheckIn checkIn) {
        String remark = checkIn.getRemark();
        //将json字符串转换成list
        List<ElderFamilyVo> elderFamilyList = JSON.parseArray(remark, ElderFamilyVo.class);
        return elderFamilyList;
    }

    /**
     * 查询入住配置信息
     * @param elder
     * @param contract
     * @param checkInId
     * @return
     */
    public CheckInConfigVo selectCheckInConfigVo(Elder elder, Contract contract,Long checkInId) {
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(Wrappers.<CheckInConfig>lambdaQuery().eq(CheckInConfig::getCheckInId, checkInId));
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        BeanUtils.copyProperties(checkInConfig, checkInConfigVo);
        checkInConfigVo.setStartDate(contract.getStartDate());
        checkInConfigVo.setEndDate(contract.getEndDate());
        checkInConfigVo.setBedNumber(elder.getBedNumber());
        return checkInConfigVo;
    }
    /**
     * 查询老人信息
     * @param elder
     * @return
     */
    public CheckInElderVo selectCheckInElderVo(Elder elder) {
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        BeanUtils.copyProperties(elder, checkInElderVo);
        Integer age = getAge(elder);
        checkInElderVo.setAge(age);
        return checkInElderVo;
    }

    /**
     * 根据身份证号计算精确年龄
     * @param elder
     * @return
     */
    private Integer getAge(Elder elder) {
        try {
            String idCardNo = elder.getIdCardNo();
            if (idCardNo == null || idCardNo.length() < 18) {
                return null;
            }

            // 解析出生日期
            String birthYear = idCardNo.substring(6, 10);
            String birthMonth = idCardNo.substring(10, 12);
            String birthDay = idCardNo.substring(12, 14);

            LocalDate birthDate = LocalDate.of(
                    Integer.parseInt(birthYear),
                    Integer.parseInt(birthMonth),
                    Integer.parseInt(birthDay)
            );

            // 计算精确年龄
            LocalDate currentDate = LocalDate.now();
            return (int) ChronoUnit.YEARS.between(birthDate, currentDate);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 新增入住配置
     *
     * @param dto
     * @param checkIn
     */
    private void saveCheckInConfig(CheckInApplyDto dto, CheckIn checkIn) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(dto.getCheckInConfigDto(), checkInConfig);
        Long checkInId = checkIn.getId();
        checkInConfig.setCheckInId(checkInId);
        checkInConfigMapper.insert(checkInConfig);
    }

    /**
     * 新增入住
     *
     * @param dto
     * @param elder
     * @return
     */
    private CheckIn saveCheckIn(CheckInApplyDto dto, Elder elder) {
        CheckIn checkIn = new CheckIn();
        checkIn.setElderId(elder.getId());
        checkIn.setElderName(elder.getName());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setNursingLevelName(dto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setStartDate(dto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(dto.getCheckInConfigDto().getEndDate());
        checkIn.setBedNumber(elder.getBedNumber());
        checkIn.setRemark(JSON.toJSONString(dto.getElderFamilyDtoList()));
        checkIn.setStatus(0);
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    /**
     * 新增签约办理
     *
     * @param dto
     * @param elder
     */
    private void saveContract(CheckInApplyDto dto, Elder elder) {
        Contract contract = new Contract();
        //属性拷贝
        BeanUtils.copyProperties(dto.getCheckInContractDto(), contract);
        String contractNo = "ZZYL" + CodeGenerator.generateContractNumber();
        contract.setContractNumber(contractNo);
        contract.setElderId(elder.getId());
        contract.setElderName(elder.getName());
        // 状态、开始时间、结束时间
        // 签约时间小于等于当前时间，合同生效中
        LocalDateTime StartDate = dto.getCheckInConfigDto().getStartDate();
        LocalDateTime EndDate = dto.getCheckInConfigDto().getEndDate();
        Integer status = StartDate.isBefore(LocalDateTime.now()) ? 1 : 0;
        contract.setStatus(status);
        contract.setStartDate(StartDate);
        contract.setEndDate(EndDate);
        contractMapper.insert(contract);
    }

    /**
     * 新增或更新老人
     *
     * @param dto
     * @param bed
     * @return
     */
    private Elder saveElder(CheckInApplyDto dto, Bed bed) {
        Elder elder = new Elder();
        //属性拷贝
        BeanUtils.copyProperties(dto.getCheckInElderDto(), elder);
        elder.setBedNumber(bed.getBedNumber());
        elder.setBedId(bed.getId());
        elder.setStatus(1);
        // 查询老人信息，（身份证号、状态不为1）
        Elder newElder = elderMapper.selectOne(Wrappers.<Elder>lambdaQuery().eq(Elder::getIdCardNo, dto.getCheckInElderDto().getIdCardNo()));
        if (ObjectUtils.isEmpty(newElder)) {
            elderMapper.insert(elder);
        } else {
            elderMapper.updateById(elder);
        }
        return elder;
    }
}
